<script setup lang="ts">
  import { PropType, ref } from 'vue'
  import { useFaultsUpdateVisibleType } from '@/services/pages/know/fault'
  import { FormInstance } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'

  const { updateViisbleTypeLoading, updateVisible } = useFaultsUpdateVisibleType()

  defineOptions({
    name: 'VisibleTypeFaults',
  })

  const props = defineProps({
    ids: {
      type: Array as PropType<Array<string>>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
  }>()

  const visible = defineModel('visible', { type: Boolean, default: false })
  const form = ref<{ visibleType: 1 | 2 | 3 }>({
    visibleType: 1,
  })
  const rules = ref({
    visibleType: [{ required: true, message: '请选择可见类型', trigger: ['change', 'blur'] }],
  })
  const formInstance = ref<FormInstance | null>(null)

  const onCancel = () => {
    form.value.visibleType = 1
    visible.value = false
  }

  const onConfirm = async () => {
    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        const res = await updateVisible(props.ids, form.value.visibleType)
        if (res.code === 20000) {
          HMessage.success(infoTip.know.fault.list.multipleUpdateVisibleTypeSuccess)
          emits('update-list')
          onCancel()
          return
        }
        HMessageBox.error(res.message)
      } catch (error) {
        // 校验失败
      }
    }
  }
</script>

<template>
  <h-dialog v-model="visible" title="批量更新可见类型" :loading="updateViisbleTypeLoading">
    <el-form
      ref="formInstance"
      label-position="top"
      inline-message
      class="modal_form_content"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="可见类型" prop="visibleType">
        <el-select v-model="form.visibleType" placeholder="请选择可见类型">
          <el-option :value="1" label="全部可见"></el-option>
          <el-option :value="2" label="网点可见"></el-option>
          <el-option :value="3" label="公司可见"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="onCancel">取消</h-button>
    </template>
  </h-dialog>
</template>
